package cn.hznc.controller.toolAnalyze;

import cn.hznc.aspect.BusinessType;
import cn.hznc.aspect.Log;
import cn.hznc.controller.service.toolAnalyze.ToolImportAnalysisService;
import cn.hznc.domain.entity.ToolImportAnalysisEntity;
import cn.hznc.domain.response.ResponseBody;
import cn.hznc.excel.ToolImportAnalysisListener;
import cn.hznc.exception.SystemException;
import cn.hznc.utils.FileUploadUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;


@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/toolImportAnalysis")
@Slf4j
public class ToolImportAnalysisController {

    @Resource
    private ToolImportAnalysisService toolImportAnalysisService;

    @RequestMapping(value = "/importToolAnalysis", method = RequestMethod.POST)
    @Log(title = "导入一级库库存" , businessType = BusinessType.INSERT)
    public ResponseBody<Boolean> importAllotEmployee(@RequestPart("file") MultipartFile file,
                                                     @RequestParam(value = "warehouseId",required = false) String warehouseId,
                                                     @RequestParam(value = "operator",required = false)String operator) {
        List<ToolImportAnalysisEntity> toolImportAnalysisEntities = new ArrayList<>();
        try {
            ToolImportAnalysisListener toolImportAnalysisListener = new ToolImportAnalysisListener(toolImportAnalysisEntities);
            FileUploadUtil.checkCommonFile(file);
            EasyExcel.read(file.getInputStream(),ToolImportAnalysisEntity.class, toolImportAnalysisListener).extraRead(CellExtraTypeEnum.MERGE).headRowNumber(2).autoCloseStream(true).sheet().doRead();
            toolImportAnalysisService.importToolAnalysis(toolImportAnalysisListener.getImportData(),Integer.valueOf(warehouseId),operator);
        } catch (IOException ex) {
            log.error("importOrder error========》", ex);
        } catch (SystemException systemException) {
            log.error("importOrder error========》msg：{}", systemException.getMsg());
            return ResponseBody.error(systemException.getCode(), systemException.getMsg());
        } catch (IllegalAccessException e) {
            log.error("importOrder error========》" , e.getMessage());
            return ResponseBody.error("1001" , "解析错误1");
        } catch (ParseException e) {
            log.error("importOrder error========》" , e.getMessage());
            return ResponseBody.error("1002" , "解析错误2");
        }
        return ResponseBody.success(Boolean.TRUE);
    }
}
